package 基础语法.网络编程;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;

public class TCP_文件传输 {
    public static void main(String[] args) {
        Thread senThread = new Thread() {
            @Override
            public void run() {
                try {
                    sendData();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        Thread receiveThread = new Thread() {
            @Override
            public void run() {
                try {
                    receiveData();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        // receiveThread.setPriority(10000);
        receiveThread.start();// 必须先启动

        // senThread.setPriority(100000);
        senThread.start();

    }

    static void sendData() throws Exception {
        // 1.
        // 在创建对象是会尝试连接服务器，如果连接不上，代码报错
        Socket socket = new Socket("127.0.0.1", 8080);

        // 2.从连接中获取输出流
        OutputStream os = socket.getOutputStream();// SocketOutputStream

        FileInputStream fi = new FileInputStream(new File("E:\\桌面\\JAVA面试\\Java语法与工具学习\\基础语法\\网络编程\\TCP_learn.java"));

        os.write(fi.readAllBytes());// 发送数据
        socket.shutdownOutput();// 告知对方结束发送，必须要加，不然服务端bufferedReader.readLine()不会结束，一直卡折

        System.out.println("等待反馈");
        InputStream is = socket.getInputStream();
        InputStreamReader ir = new InputStreamReader(is);
        BufferedReader bufferedReader = new BufferedReader(ir);
        System.out.println(bufferedReader.readLine());

        os.close();
        bufferedReader.close();
        socket.close();

    }

    static void receiveData() throws Exception {
        // 1.
        ServerSocket serverSocket = new ServerSocket(8080);// 端口保持与发送端一致
        // 2.监听客户端的连接
        Socket socket = serverSocket.accept();
        System.out.println("0000");

        // 3.从连接通道中获取输入流读取数据
        InputStream inputStream = socket.getInputStream();// SocketInputStream

        FileOutputStream fileOutputStream = new FileOutputStream(new File("./接收到的数据+"+UUID.randomUUID()+".txt"));

        fileOutputStream.write(inputStream.readAllBytes());

        fileOutputStream.close();

        OutputStream os = socket.getOutputStream();
        os.write("我已接收到数据".getBytes());// 发送反馈

        socket.close();

        os.close();

    }

}
